# _*_ coding: utf-8 _*_
# @Author   : Wei Yue
# @Time     : 2023-05-16 12:50
# @Function :
import itertools

import pandas
import pandas as pd
from scipy.interpolate import LinearNDInterpolator


# 构建自己的2D插值工具
# 如果超过边界就取边界值
class MyInterpolate2D:
    f1 = None

    def __init__(self, x, y, df: pd.DataFrame):
        self.x = x
        self.y = y
        coords = list(itertools.product(x, y))
        z = df.values.flatten()
        self.f1 = LinearNDInterpolator(coords, z)

    @classmethod
    def createByDf(cls, df: pandas.DataFrame):
        x = df.index.values
        y = df.columns.values
        return cls(x, y, df)

    def interp(self, x1, y1):
        xmin = min(self.x)
        xmax = max(self.x)
        ymin = min(self.y)
        ymax = max(self.y)
        if x1 < xmin:
            x1 = xmin
        if x1 > xmax:
            x1 = xmax
        if y1 < ymin:
            y1 = ymin
        if y1 > ymax:
            y1 = ymax
        z1 = self.f1(x1, y1)
        return z1

    def interpArr(self,Xarr,Yarr):
        list = []
        size = len(Xarr)
        for i in range(size):
            z = self.interp(Xarr[i],Yarr[i])
            list.append(z.tolist())
        return list


if __name__ == '__main__':
    path = 'C:/Users/Lenovo/Desktop/MotorSimulink/motorMap.xlsx'
    Ld_table = pd.read_excel(path, sheet_name='LdMap', index_col=0)
    x = Ld_table.index.values
    y = Ld_table.columns.values
    myObj = MyInterpolate2D(x, y, Ld_table)
    myObj2 = MyInterpolate2D.createByDf(Ld_table)
    print(myObj2.interp(10,0))
    print(myObj.interp(10, 0))
